﻿

Public Class frmMain

    Private IsClosing As Boolean = False
    Private dtDefinitions As New DataAccess.Definitions

    Private Sub btnTranslate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTranslate.Click


        txtSource.Text = txtSource.Text.Trim

        txtTarget.Text = Translate(txtSource.Text, _
                                   cmbSource.SelectedValue, _
                                   cmbTarget.SelectedValue)

        If txtTarget.Text.Trim.Length > 0 Then

            AddHistory(txtSource.Text)

        End If

        txtSource.SelectAll()

    End Sub

    Private Function LoadURL(ByVal url As String) As Byte()

        Dim myRequest As System.Net.WebRequest
        Dim myResponse As System.Net.WebResponse
        Dim myResponseStream As System.IO.Stream

        Dim Index As Long = 0
        Dim HTMLBytes As List(Of Byte)
        Dim HTMLSingleByte As Integer


        myRequest = System.Net.HttpWebRequest.Create(url)
        myResponse = myRequest.GetResponse
        myResponseStream = myResponse.GetResponseStream

        HTMLBytes = New List(Of Byte)

        '*  Read HTML Source Code
        Do

            HTMLSingleByte = myResponseStream.ReadByte()

            If HTMLSingleByte < 0 Then
                '*  End of the page.
                Exit Do
            End If

            HTMLBytes.Add(HTMLSingleByte)

            Index += 1

        Loop While Index > 0

        myRequest = Nothing
        myResponse.Close()
        myResponseStream.Close()

        Return HTMLBytes.ToArray

    End Function

    Private Function Translate(ByVal srcWord As String, ByVal srcLang As String, ByVal trgLang As String) As String

        Dim trgWord As String = String.Empty

        trgWord = DataAccess.Words.TranslateDb(srcWord, srcLang, trgLang)

        If String.IsNullOrEmpty(trgWord) Then

            trgWord = TranslateOnline(srcWord, srcLang, trgLang)

            If Not String.IsNullOrEmpty(trgWord) Then
                DataAccess.Words.AddToDb(srcWord, srcLang, trgWord.Trim, trgLang)
            End If

        End If

        Return trgWord

    End Function

    Private Function TranslateOnline(ByVal word As String, ByVal srcLang As String, ByVal trgLang As String) As String

        Dim byteResponse As Byte()
        Dim strResponse As String
        Dim Index1 As Integer
        Dim Index2 As Integer
        Dim Index3 As Integer


        '*  Get Page Content 
        '*   Get Page Content Byte Array
        byteResponse = LoadURL("http://translate.google.com/m?hl=en&sl=" + srcLang + "&tl=" + trgLang + "&ie=UTF-8&prev=_m&q=" + txtSource.Text)
        '*   Convert Byte Array to String
        strResponse = System.Text.Encoding.GetEncoding(dtDefinitions.GetCodePageByCode(trgLang)).GetString(byteResponse)


        Index1 = strResponse.IndexOf(dtDefinitions.GetNameByCode(trgLang))
        If Index1 > 0 Then
            Index1 = strResponse.IndexOf("<div", Index1)
            If Index1 > 0 Then
                Index1 = strResponse.IndexOf(">", Index1)
                If Index1 > 0 Then

                    Index2 = strResponse.IndexOf("</div>", Index1)
                    If Index2 > 0 Then
                        Dim strResult As String = strResponse.Substring(Index1 + 1, Index2 - Index1 - 1)
                        strResult = strResult.Replace("&#1740;", "ی")
                        strResult = strResult.Replace("&#7889;", "ố")
                        strResult = strResult.Replace("&#7915;", "ừ")
                        If strResponse.Length > Index2 + 32 Then
                            If strResponse.Substring(Index2, 32) = "</div><div dir=""ltr"" class=""t0"">" Then
                                Index3 = strResponse.IndexOf("</div>", Index2 + 30)
                                strResult = strResponse.Substring(Index2 + 32, Index3 - Index2 - 32)
                            End If
                            Return strResult
                        Else
                            Return ""
                        End If
                    End If
                End If

            End If
        End If

        Return String.Empty

    End Function

    Private Sub AddHistory(ByVal word As String)

        For Each strItem As String In lbHistory.Items
            If strItem.ToUpper = word.Trim.ToUpper Then
                Exit Sub
            End If
        Next

        lbHistory.Items.Insert(0, word)

        If lbHistory.Items.Count > 10 Then
            lbHistory.Items.RemoveAt(lbHistory.Items.Count - 1)
        End If

    End Sub

    Private Sub lbHistory_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lbHistory.SelectedIndexChanged

        If lbHistory.Items.Count < 0 OrElse lbHistory.SelectedItems.Count < 0 Then
            Exit Sub
        End If

        txtSource.Text = lbHistory.SelectedItem
        txtTarget.Text = Translate(txtSource.Text, "en", "fa")

    End Sub

    Private Sub txtEng_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtSource.GotFocus
        txtSource.SelectAll()
    End Sub

    Private Sub frmMain_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing

        If Not IsClosing Then
            Me.WindowState = FormWindowState.Minimized
            e.Cancel = True
        End If

    End Sub

    Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        tmrKeyReader.Enabled = True

        cmbSource.DataSource = dtDefinitions
        cmbSource.DisplayMember = "Name"
        cmbSource.ValueMember = "Code"
        cmbTarget.DataSource = dtDefinitions.Copy
        cmbTarget.DisplayMember = "Name"
        cmbTarget.ValueMember = "Code"


        '*  Initial translation 
        cmbSource.SelectedValue = My.Settings.defaultSourceLanguage
        cmbTarget.SelectedValue = My.Settings.defaultTargetLanguage
        txtSource.Text = "Welcome" 'DataAccess.Words.TranslateDb("Welcome", "en", My.Settings.defaultSourceLanguage)
        btnTranslate.PerformClick()

    End Sub

    Private Sub frmMain_SizeChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.SizeChanged

        If Me.WindowState = FormWindowState.Minimized Then
            Me.ShowInTaskbar = False
        Else
            Me.ShowInTaskbar = True
        End If

    End Sub

    Private Sub NotifyIcon1_MouseDoubleClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles NotifyIcon1.MouseDoubleClick

        Me.WindowState = FormWindowState.Normal

    End Sub

    Private Sub tmrKeyReader_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrKeyReader.Tick

        Dim keyF10 As New MyKeyboard(Keys.F10)

        If keyF10.KeyState() AndAlso My.Computer.Keyboard.ShiftKeyDown Then

            Dim strClipboard As String = String.Empty

            Try

                strClipboard = Clipboard.GetText

            Catch ex As Exception

                strClipboard = String.Empty

            End Try

            If Not String.IsNullOrEmpty(strClipboard) Then

                Me.WindowState = FormWindowState.Normal
                txtSource.Text = strClipboard
                btnTranslate_Click(btnTranslate, EventArgs.Empty)

            End If

        End If
        keyF10 = Nothing

    End Sub

    Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click

        IsClosing = True

        '*  Save default languages during closing
        My.Settings.defaultSourceLanguage = cmbSource.SelectedValue
        My.Settings.defaultTargetLanguage = cmbTarget.SelectedValue
        My.Settings.Save()


        Me.Close()

    End Sub

    Private Sub ToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem1.Click
        My.Forms.frmAbout.ShowDialog()
    End Sub

End Class
